<template>
  <div class="w-3 middle flex flex-column">
    <div class="flex justify-content-between align-items-center p-2">
      <span class="p-input-icon-left">
        <i class="pi pi-search" />
        <InputText v-model="searchInput" style="width: 98%;" size="small" placeholder="搜索" />
      </span>
      <i class="pi pi-plus cursor-pointer" @click="handleAddGroup"></i>
    </div>
    <div class="overflow-y-auto">
      <div :class="{ 'flex align-items-center p-1 item ': true, 'activeItem': isActive(item as TUserModel & TGroupModel) }"
        v-for="item in groupFriendList" @click="handleChange(item as TUserModel & TGroupModel)">
        <!-- @vue-ignore -->
        <Avatar :image="item?.avatar" class="" size="large" shape="circle" />
        <div class="flex flex-column ml-2">
          <!-- @vue-skip -->
          <span>{{ item?.username || item?.groupName }}</span>
          <span class="content">{{ item.messages?.[0]?.content }}</span>
        </div>
      </div>
    </div>
  </div>
  <AddGroupModal v-model:groupVisible="groupVisible" :friendList="chatStore.friendGroupList.friendData" />
</template>

<script setup lang="ts">
import { Avatar, InputText } from '@/utils/primevue'

import useChatStore from '@/stores/chat'
import type { TAllData, TFriend, TGroup, TGroupModel } from '@/stores/typings/chat';
import { computed, ref } from 'vue';
import type { TUserModel } from '@/stores/typings/user';
import AddGroupModal from './AddGroupModal.vue';

// type TProps = {}

// const props = defineProps<TProps>()
// const emits = defineEmits([])
const searchInput = ref<string>()
const groupVisible = ref(false)



// 朋友和群组数据
const groupFriendList = computed(() => {
  const allData = chatStore.friendGroupList
  if (allData) {
    return [...allData.friendData, ...allData.groupData]
  }
  return []
})


const chatStore = useChatStore()

const handleChange = (item: TFriend & TGroup) => {
  // 查询当前点击的朋友的聊天记录
  chatStore.currentFriend = item
  console.log('item', item)
  if (item.groupId) {
    chatStore.joinGroupSocket()
    chatStore.getGroupMessage()
  }else {
    chatStore.joinFriendSocket()
    chatStore.getFrendMessage()
  }


}

const isActive = (item: TFriend & TGroup) => {
  const id = item.groupId ? item.groupId : item.userId
  if (chatStore.currentFriend.groupId) {
    return id === chatStore.currentFriend.groupId
  } else {
    return id === chatStore.currentFriend.userId
  }
}


// 添加群组
const handleAddGroup = () => {
  groupVisible.value = true
}

</script>

<style scoped lang="scss">
.middle {
  background: #0000001f;

  .item {
    background: #1812121f;
    cursor: pointer;
  }

  .activeItem {
    background-color: #00000054;
  }

  .content {
    color: #999;
    font-size: 12px;
  }
}
</style>
